package com.promise.jokerdream.work.signin.after

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.response.pc.QueryEnchantResponse
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 附魔工作
class EnchantWork(override val uin: String): BaseWork(uin) {

    override val name: String
        get() = "附魔"

    override val priority: Int
        get() = 9

    private val gameApi = GameApi.Companion.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.Companion.getInstance(AppContext.get()) }

    override suspend fun executeWork(): WorkResult {
        try {
            // 查询附魔信息
            val queryResult = gameApi.queryEnchant()
            return queryResult.foldWithApiException(
                onSuccess = { response ->
                    processEnchantMissions(response)
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            return WorkResult.Failure(e, e.message)
        }
    }

    private suspend fun processEnchantMissions(response: QueryEnchantResponse): WorkResult {
        // 遍历所有任务，查找status=1的任务进行领取
        for (mission in response.missions) {
            if (mission.status == 1) {
                val claimResult = gameApi.claimEnchant(mission.id)
                claimResult.foldWithApiException(
                    onSuccess = { claimResponse ->
                        historyManager.addHistory(name, claimResponse.getDescription())
                    },
                    onFailure = { code, msg ->
                        historyManager.addHistory(name, msg, code)
                    }
                )
            }
        }

        return WorkResult.Success
    }
}